package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.author.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojo.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author TheCai
 * @date 2021/5/24 23:05
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>
    implements ApUserRealnameService {

  @Autowired
  ApUserMapper apUserMapper;

  @Override
  public ResponseResult loadListByStatus(AuthDto dto) {
    // 1 参数检查
    dto.checkParam();
    if (dto == null) {
      throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
    }

    // 2 条件查询
    IPage<ApUserRealname> realnamePage = new Page<>(dto.getPage(), dto.getSize());
    LambdaQueryWrapper<ApUserRealname> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    if (dto.getStatus() != null) {
      lambdaQueryWrapper.eq(ApUserRealname::getStatus, dto.getStatus());
    }
    IPage<ApUserRealname> resultPage = page(realnamePage, lambdaQueryWrapper);

    ResponseResult responseResult =
        new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());

    responseResult.setData(resultPage.getRecords());
    // 3 返回结果
    return responseResult;
  }

  @GlobalTransactional
  @Override
  public ResponseResult updateStatusById(AuthDto dto, Short status) {
    // 1. 检查参数
    if (null == dto || null == dto.getId()) {
      CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    // 2. 根据ID查询实名认证信息
    ApUserRealname userRealname = getById(dto.getId());
    if (userRealname == null) {
      CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
    }
    // 3. 判断实名认证状态是否为待审核
    if (userRealname.getStatus().intValue() != 1) {
      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
    // 4. 查询实名认证用户关联的ap_user信息
    ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
    if (apUser == null) {
      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联用户信息不存在");
    }

    // 5. 更新实名认证信息
    userRealname.setStatus(status);
    userRealname.setUpdatedTime(new Date());
    // 查看有没有驳回消息
    if (StringUtils.isNotBlank(dto.getMsg())) {
      // 有的话写入数据库
      userRealname.setReason(dto.getMsg());
    }
    updateById(userRealname);
    // 6. 如果 审核结果为 通过(9) 生成自媒体账号，生成作者信息
    if (status.equals(AdminConstants.PASS_AUTH)) {
      //      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);

      WmUser wmUser = this.creatWmUser(apUser);
      if (wmUser == null || wmUser.getId() == null) {
        CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "创建自媒体用户失败");
      }
      ResponseResult responseResult = this.creatApAuthor(wmUser);
      if (responseResult.getCode()!=0){
        CustException.cust(AppHttpCodeEnum.SERVER_ERROR, responseResult.getErrorMessage());
      }

      // 7. 当前用户为自媒体人
//      apUser.setFlag((short) 1);
//      apUser.setIdentityAuthentication(true);
//      apUserMapper.insert(apUser);
  }
//    int i=1/0;
    return ResponseResult.okResult();
  }

  @Autowired
  ArticleFeign articleFeign;
  /** 创建作者信息 */
  public ResponseResult creatApAuthor(WmUser wmUser) {
    ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
    if (apAuthor != null) {
      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息已存在");
    }
    apAuthor=new ApAuthor();
    apAuthor.setName(wmUser.getName());
    apAuthor.setType(2);
    apAuthor.setUserId(wmUser.getApUserId());
    apAuthor.setCreatedTime(new Date());
    apAuthor.setWmUserId(wmUser.getId());
  return   articleFeign.save(apAuthor);
  }

  @Autowired
  WemediaFeign wemediaFeign;

  /**
   * 创建自媒体用户
   * @param apUser
   * @return
   */
  public WmUser creatWmUser(ApUser apUser){
    WmUser wmUser = wemediaFeign.findByName(apUser.getName());
    if (wmUser!=null){
      CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "自媒体用户信息已存在");
    }
    wmUser=new WmUser();
//    wmUser.setApUserId(apUser.getId());
//    wmUser.setName(apUser.getName());
//    wmUser.setPassword(apUser.getPassword());
//    wmUser.setSalt(apUser.getSalt());
//    wmUser.setImage(apUser.getImage());
//    wmUser.setPhone(apUser.getPhone());
//    wmUser.setStatus(AdminConstants.AD_USER_ISSTATUS);
//    wmUser.setType(0);
//    wmUser.setCreatedTime(new Date());
    BeanUtils.copyProperties(apUser,wmUser);
    wmUser.setId(null);
    wmUser.setApUserId(apUser.getId());
    return wemediaFeign.save(wmUser);
  }
}
